<template>
  <view class="page" :style="themeStyle">
    <my-search ref="mySearch" class="mySearch" :site_title="site_title" :color="app.themeConfig.text_color"></my-search>
    <view class="content">
      <view 
        :class="['banner', {bannerTop: app.themeConfig.valid == 1 }]"
        :style="{'--menusystemheight': `${menuSystemHeight}px`}"
      >
        <swiper class="swiper" circular :autoplay="true">
          <swiper-item
            v-for="(item, index) in banner"
            :key="index"
            @click="jump(item)"
          >
            <image class="img" :src="item.img" mode="scaleToFill"></image>
          </swiper-item>
        </swiper>
      </view>
      <view class="info">
        <view class="info-content flex-middle">
          <view class="info-icon">
            <image class="icon" :src="infoIcon" mode=""></image>
          </view>
          <!-- #ifndef MP-WEIXIN -->
          <u-notice-bar
            mode="horizontal"
            :speed="100"
            :isCircular="true"
            :list="publicMsg"
            :volume-icon="false"
            bg-color="transparent"
            :color="app.themeConfig.text_color"
            padding="0"
            style="flex: 1"
          ></u-notice-bar>
          <!-- #endif -->
          <!-- #ifdef MP-WEIXIN -->
          <u-notice-bar
            mode="horizontal"
            :speed="100"
            :isCircular="true"
            :list="publicMsg"
            :volume-icon="false"
            bg-color="transparent"
            color="#ffffff"
            padding="0"
            style="width: 100%; overflow: hidden"
          ></u-notice-bar>
          <!-- #endif -->
        </view>
      </view>
      <!-- <view class="part_box">
        <view
          class="part"
          @click="navigate(item)"
          v-for="item in partData"
          :key="item.id"
        >
          <image class="part_img" :src="item.icon" mode=""></image>
          <text class="part_text">{{ item.name }}</text>
        </view>
      </view> -->
      <view class="part">
        <swiper :class="[`line-${navType}`, 'part-swiper']" circular :indicator-dots="[3, 4].includes(navType)" :autoplay="false">
          <swiper-item v-for="(item, index) in pagePartData " :key="index + 1920">
            <view class="part_box">
              <view
                class="part"
                @click="navigate(childItem)"
                v-for="childItem in item"
                :key="childItem.id"
              >
                <image class="part_img" :src="childItem.icon" mode=""></image>
                <text class="part_text">{{ childItem.name }}</text>
              </view>
            </view>
          </swiper-item>
        </swiper>
      </view>

      <view>
        <u-popup
          v-model="showtel"
          mode="center"
          border-radius="14"
          length="60%"
        >
          <view class="tel-flex">
            <view class="flex-box" @click="onselect(1)">
              <image class="tel-pic" :src="picture" mode=""></image>
              <view class="txt-size"> 电话联系 </view>
            </view>

            <view
              class="flex-box lf-border"
              v-if="showline"
              @click="onselect(2)"
            >
              <image class="tel-pic" :src="linpic" mode=""></image>
              <view class="txt-size"> 在线客服 </view>
            </view>
          </view>
        </u-popup>
      </view>
      <view class="sale">
        <view class="sale_box" v-if="saleData">
          <view class="time">
            <text class="text">{{
              saleData.status == 0 ? "距离开始" : "距离结束"
            }}</text>
            <u-count-down
              :timestamp="countDown"
              separator="zh"
              :color="app.themeConfig.text_color"
              :bg-color="app.themeConfig.text_color2"
            ></u-count-down>
          </view>
          <view class="sale_content" @click="toCheapSale">
            <view
              class="goods"
              v-for="(item, index) in saleData.goods_list_3"
              :key="index"
            >
              <image class="img" :src="item.img" mode="aspectFit"></image>
              <text class="name">{{ item.goods_name }}</text>
              <!-- <view class="tag">特卖</view> -->
              <view v-show="canshowprice" class="unit"
                >活动价：<text class="price">{{ item.price }}</text
                >/{{ item.goods_spu.spu_unit.title }}</view
              >
              <view v-show="canshowprice" class="unit old"
                >原价：<text class="price">{{ item.market_price }}</text
                >/{{ item.goods_spu.spu_unit.title }}</view
              >
            </view>
          </view>
        </view>
      </view>

      <view class="activity">
        <view class="activity_box" v-if="parts.length > 0">
          <view class="title">精选专题</view>
          <view class="style1 flex-btw" v-if="parts.length == 1">
            <image
              :src="parts[0].img"
              @click="toPartDetail(parts[0].name, parts[0].id)"
              mode="scaleToFill"
            >
            </image>
          </view>
          <view class="style2 flex-btw" v-else-if="parts.length == 2">
            <view class="left">
              <image
                :src="parts[0].img"
                @click="toPartDetail(parts[0].name, parts[0].id)"
                mode="scaleToFill"
              >
              </image>
            </view>
            <view class="right">
              <image
                :src="parts[1].img"
                @click="toPartDetail(parts[1].name, parts[1].id)"
                mode="scaleToFill"
              >
              </image>
            </view>
          </view>
          <view class="style3 flex-btw" v-else-if="parts.length == 3">
            <view class="left">
              <image
                :src="parts[0].img"
                @click="toPartDetail(parts[0].name, parts[0].id)"
                mode="scaleToFill"
              >
              </image>
            </view>
            <view class="right">
              <image
                :src="parts[1].img"
                @click="toPartDetail(parts[1].name, parts[1].id)"
                mode="scaleToFill"
              >
              </image>
              <image
                :src="parts[2].img"
                @click="toPartDetail(parts[2].name, parts[2].id)"
                mode="scaleToFill"
              >
              </image>
            </view>
          </view>
        </view>
      </view>
      <view 
        class="homeCategory"
        :style="{'--menusystemheight': `${menuSystemHeight}px`}"
        v-if="subjectList.length"
      >
        <scroll-view 
          enable-flex 
          scroll-x
          scroll-left="0"
          class="category-scroll"
        >
          <view class="category">
            <view 
              :class="['category-name flex-center',{active: subjectIndex == index}]" 
              v-for="(item,index) in subjectList"
              :key="index" 
              @click="changeSubject(item,index)"
            >
              {{ item.name }}
            </view>
          </view>
        </scroll-view>
      </view>
      <scroll-view 
        scroll-y 
        :scroll-top="goodsScrollTop"
        class="goodsScroll" 
        :style="{'--menusystemheight': `${menuSystemHeight}px`}"
        @scrolltolower="handMore"
        v-if="subjectList.length"
      >
        <view 
        class="recommend_box"
        :style="{
          'grid-template-columns': `repeat(${display_row},${goodsWidthMap[display_row]})`,
          display: !goodsList.length ? 'block' : 'grid',
        }"
      >
        <view
          class="goods"
          @click="detailPage(item.id)"
          v-for="(item, index) in goodsList"
          :key="index"
          :style="{
            width: goodsWidthMap[display_row],
          }"
        >
          <view class="tags" v-if="item.datum.length">
            <view
              class="tag"
              v-for="(y, index) in item.datum"
              :key="index"
              >{{ y.title }}</view
            >
          </view>
          <view
            class="img"
            :style="{
              width: goodsWidthMap[display_row],
              height: goodsHeightMap[display_row],
            }"
          >
            <image :src="item.img" mode="aspectFit"></image>
          </view>
          <view
            class="goods-content"
            :style="{
              width: goodsWidthMap[display_row],
            }"
          >
            <view class="name">{{ item.name }}</view>
            <view class="price">
              <text class="unit" v-show="canshowprice"
                ><text class="price"
                  >{{ item.showPrice
                  }}<text
                    v-if="
                      item.spu.length == 1 && item.spu[0].current_price == 0
                    "
                    style="font-size: 24rpx"
                  >
                    /{{ item.spu[0].unit }}</text
                  ></text
                ></text
              >
              <image
                v-if="display_row != 3"
                @click.stop="showCart(index)"
                class="icon shop"
                src="/static/image/addcart.svg"
                mode=""
              >
              </image>
            </view>
          </view>
        </view>
        <view class="noGoods" v-if="!goodsList.length && !goodsLoading">
          <image :src="nodataImg" mode="aspectFit"></image>
          <view>暂无数据~</view>
        </view>
        </view>
        <view class="moreText" v-if="goodsList.length">
          <view v-if="goodsList.length < alltotal && !goodsLoading">上拉加载更多</view>
          <view v-if="goodsLoading" class="flex-middle">
            <u-loading class="goodsLoading" mode="flower"></u-loading>
            <text>努力加载中...</text>
          </view>
          <view v-if="goodsList.length >= alltotal">没有更多了</view>
        </view>
      </scroll-view>
    </view>
    <my-tabar ref="tabar" current="0"></my-tabar>

    <my-addcart
      ref="minicart"
      :canshowprice="canshowprice"
      @tabBarTag="changeTabBarTag"
    ></my-addcart>

    <u-mask v-if="coupons.length > 0" :show="showMask">
      <view class="warp">
        <view class="rect">
          <view class="pics">
            <image
              src="https://copartner.oss-cn-beijing.aliyuncs.com/logo/2312/08/5e6qtCZ9IEZSsKjbSuSe0JhShCbLjHjeU20CV3VN.png"
              mode="aspectFit"
            ></image>
            <view class="abos">
              <view class="copon_box copon flex-btw" v-for="item in coupons" :key="item.id">
                <view class="left">现金券</view>
                <view class="center flex-btw">
                  <view class="center_left">
                    <view class="price">￥{{ item.coupons.money }}</view>
                    <view
                      class="info flex-center"
                      @click="alertInfo(item.coupons.describe)"
                    >
                      <u-icon name="question-circle"></u-icon>
                      <text class="info_text">使用说明</text>
                    </view>
                  </view>
                  <view class="center_right">
                    <view class="rule" v-if="item.type == 1"
                      >满{{ item.coupons.order_money_limit }}使用
                    </view>
                    <view class="rule" v-else-if="item.type == 2">无门槛</view>
                    <view class="limit" v-if="item.coupons.get_limit">
                      每位用户限制{{ item.coupons.get_num }}张</view
                    >
                    <view class="limit" v-else>不限量</view>
                    <view class="time" v-if="item.coupons.expire_type == 1">
                      {{ parseTime(item.coupons.start_time) }}~{{
                        parseTime(item.coupons.end_time)
                      }}
                    </view>
                    <view
                      class="time"
                      v-else-if="item.coupons.expire_type == 2"
                    >
                      限{{ item.coupons.expire_days }}天内使用</view
                    >
                  </view>
                </view>
                <view class="right" @click="toCouponMy">去查看</view>
              </view>
            </view>
          </view>
        </view>
        <u-icon
          @click="showMask = false"
          name="close-circle"
          size="60"
          color="#fff"
          class="close_icon"
        ></u-icon>
      </view>
    </u-mask>

    <u-modal
      v-model="info.show"
      :content="info.value"
      title="使用说明"
      confirm-color="#40AE36"
    ></u-modal>

    <!-- <u-mask v-if="coupons.length>0" :show="showMask" @click="" class="flex-center">
			<view class="mask_content">
				<view class="relat">
					<image class="couponbg" :src="couponbg" mode="aspectFit"></image>
					<view class="box">
						<view class="coupons">
							<view class="copon_box copon flex-btw" v-for="item in coupons">
								<view class="left">{{item.type==1?'普通券':'现金券'}}</view>
								<view class="center flex-btw">
									<view class="center_left">
										<view class="price">￥{{item.coupons.money}}</view>
										<view class="info flex-center">
											<u-icon name="question-circle"></u-icon>
											<text class="info_text">使用说明</text>
										</view>
									</view>
									<view class="center_right">
										<view class="rule" v-if="item.type==1">满{{item.coupons.order_money_limit}}使用
										</view>
										<view class="rule" v-else-if="item.type==2">无门槛</view>
										<view class="limit" v-if="item.coupons.get_limit">
											每位用户限制{{item.coupons.get_num}}张</view>
										<view class="limit" v-else>不限量</view>
										<view class="time" v-if="item.coupons.expire_type==1">
											{{parseTime(item.coupons.start_time)}}~{{parseTime(item.coupons.end_time)}}
										</view>
										<view class="time" v-else-if="item.coupons.expire_type==2">
											限{{item.coupons.expire_days}}天内使用</view>
									</view>
								</view>
								<view class="right" @click="toCouponMy">去查看</view>
							</view>
						</view>
					</view>
				</view>
				<u-icon @click="showMask=false" name="close-circle" size="60" color="#fff" class="close_icon"></u-icon>
			</view>
		</u-mask> -->
    <my-homemodel :homeModelPath="homeModelPath" v-if="homeModelShow" @close="homeModelClose" @imgClick="homeModelImgClick"></my-homemodel>
    <my-loading v-if="isLoading" text="加载中..."></my-loading>
  </view>
</template>

<script>
import { $https } from "@/static/js/request.js";
// #ifdef H5
const wx = require("jweixin-module");
// #endif
// #ifdef MP-WEIXIN
let plugin = requirePlugin("WechatSI");
// #endif
const app = getApp().globalData;
export default {
  data() {
    return {
      app,
      logo: "",
      showLogo: 0,
      nodataImg: app.nodataImg,
      loginVolid: null,
      canshowprice: null, //是否在未登录时显示价格
      infoIcon:
        "https://copartner.oss-cn-beijing.aliyuncs.com/logo/2412/03/IKqCeVdHEcdsrepKJJlrp7d0COP2wlMeeCGlV9hR.svg",
      picture: "../../static/image/tel.png",
      linpic: "../../static/image/line.png",
      banner: [],
      parts: [], //精选专题
      publicMsg: [], //通知
      partData: [],
      goodsList: [],
      saleData: null, //限时特卖
      countDown: 0, //倒计时
      page: 1,
      num: 10,
      alltotal: null,

      showMask: true,
      coupons: [], //送的购物券
      info: {
        value: "",
        show: false,
      },
      showtel: false,
      showline: false,
      wx_url: "",
      telphone: "",
      corpId: "",
      wxshare: {
        title: "小程序分享",
        path: "/pages/tabar/index",
        imageUrl: "",
        desc: "",
        content: "",
      },
      site_title: "", // 标题
      isLoading: false, // loading动画
      isGuide: false, // 是否是门店跳转来的
      // 首页弹框
      homeModelShow: false, // 状态
      homeModelPath: "", // 弹框图片
      homeredirectContent: "", // 跳转位置

      display_row: 2,
			navType: 4,
      goodsWidthMap: {
        1: '690rpx',
        2: '335rpx',
        3: '224rpx'
      },
      goodsHeightMap: {
        1: '300rpx',
        2: '335rpx',
        3: '224rpx'
      },
      subjectList: [],
      subjectIndex: 0,
      menuSystemHeight: 0, // 小程序头部高度
      goodsLoading: false, // 商品加载状态
      goodsScrollTop: 0, // 设置商品竖向滚动条位置
    };
  },
  onReady() {
    this.getInfo();
    getApp().setTitle();
  },
  computed: {
    themeStyle() {
      return `
        --theme-bg: url(${app.themeConfig.background_image || "https://copartner.oss-cn-beijing.aliyuncs.com/logo/2401/17/kBTemVLjvz0h82TJUI0WfCG896mgCffBC4vuL64K.png"});
        --theme-sale-bg: url(${app.themeConfig.sale_img || "https://copartner.oss-cn-beijing.aliyuncs.com/logo/2411/22/BW1jbbJ9uvoOp5BRKC3qvBAFQEuGgUWMBBNWjDK4.png"});
        --theme-text-color: ${app.themeConfig.text_color || "#000000"};
        --theme-time-color: ${app.themeConfig.text_color2 || "#40AE36"};
        --theme-bg-color: ${app.themeConfig.theme_color || "#F6F6F7"};
        "--length": ${this.partData.length};
      `;
    },
		//	页面展示partData，数组长度超过5，变成二维数组；示例：【1，2，3，4，5，6】 ===>>>   [[1,2,3,4,5], [6]]
		pagePartData () {
			const typeList = {
				1: 5,
				2: 10,
				3: 5,
				4: 10
			}
      // 提前获取分组的大小
      const groupSize = typeList[this.navType];
      let partData = Array.from({ length: Math.ceil(this.partData.length / groupSize) }, (_, i) => {
        // 计算当前分组的起始和结束索引
        const start = i * groupSize;
        const end = Math.min(start + groupSize, this.partData.length); // 确保不会越界
        return this.partData.slice(start, end);
      });
      // 如果有主题切换主题金刚区图片
      if(app.themeConfig.category_icon.length) {
        partData = partData.map(group=> {
          return group.map((item,index)=> {
            if(app.themeConfig.category_icon[index].img_url) {
              item.icon = app.themeConfig.category_icon[index].img_url;  // 替换为 category_icon 中的图标
            }
            return item;
          })
        })
      }
      return partData;
		},
  },
  onLoad(option) {
    if (option.isGuide) {
      this.isGuide = true;
    }
    uni.hideTabBar();
    this.loginVolid = !Boolean(uni.getStorageSync("loginVolid").is_login_index);
    this.getCommodity();
  },
  mounted(){
    // #ifdef MP-WEIXIN
    const menuSystemInfo = uni.getMenuButtonBoundingClientRect();
    this.menuSystemHeight = menuSystemInfo.height + menuSystemInfo.top;
    // #endif
  },
  onShow() {
    this.getData();
    //推荐商品只请求一次，为防止退出时没有价格，登录时也没有价格。
    // 【2021-5-31更新】因为登录也可能不给你看价格
    // if(uni.getStorageSync('copartner_token')){
    // 	this.canshowprice = true;
    // }
    // #ifdef H5
    this.isGuide = window.location.href.includes("isGuide");
    if(this.$refs.mySearch){
      let mySearch = this.$refs.mySearch;
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      mySearch.background = this.hexToRgba(app.themeConfig.text_color2,scrollTop / 200);
    }
    // #endif
    this.$nextTick(function () {
      this.changeTabBarTag();
    });
  },
  methods: {
    getData() {
      $https(
        "GETN",
        "index",
        {},
        (res) => {
          if (res.data.errcode == 0) {
            this.publicMsg = [res.data.data.notice];
            this.partData = res.data.data.nav;
            this.banner = res.data.data.poster;
            this.parts = res.data.data.project_list;
            this.coupons = res.data.data.coupons || [];
						this.navType = res.data.data.nav_num;
						// this.display_row = res.data.data.project_arrange;
            //限时特卖
            if (res.data.data.panic_buy) {
              this.saleData = res.data.data.panic_buy;
              //0即将开始，1抢购中
              var now = (new Date().getTime() / 1000).toFixed(0);
              this.countDown =
                this.saleData.status == 1
                  ? this.saleData.end_time - now
                  : this.saleData.start_time - now;
            }
            let ismain = res.data.data.user_type == 1 ? true : false;
            uni.setStorageSync("wx_pay", res.data.data.wx_pay);
            uni.setStorageSync("isMain", ismain);
            uni.setStorageSync("cartTag", res.data.data.all_cart_num);
            uni.setStorageSync("open_points", res.data.data.open_points);
            uni.setStorageSync("canshowprice", res.data.data.look_goods_detail);
            this.canshowprice = res.data.data.look_goods_detail;
            // console.log(this.canshowprice)
            this.changeTabBarTag();
          } else {
            uni.showToast({
              icon: "none",
              title: res.data.errmsg,
            });
          }
        },
        this.loginVolid
      );
    },

    getInfo() {
      this.isLoading = true;
      $https(
        "GETN",
        "loginInfo",
        {},
        (res) => {
          if(res.data.data.homepage_theme) {
            uni.setStorageSync("themeConfig", res.data.data.homepage_theme);
            if(res.data.data.homepage_theme.valid == 1) app.themeConfig = res.data.data.homepage_theme;
          }
          this.logoUrl = res.data.data.info.site_logo;
          uni.setNavigationBarTitle({
            title: res.data.data.info.site_title,
          });
          // is_group yes是集团用户 no不是集团用户
          if (res.data.data.info.is_group == "yes" && !this.isGuide) {
            this.toGiude();
          }
          this.isLoading = false;
          this.site_title = res.data.data.info.site_title;
          this.loginVolid = {
            is_login_index: res.data.data.info.is_login_index,
            is_login_my: res.data.data.info.is_login_my,
            is_login_cart: res.data.data.info.is_login_cart,
            is_login_category: res.data.data.info.is_login_category,
          };
          if (res.data.data.info.is_login_index == 0) {
            this.showBackIcon = true;
          }
          this.wxshare.title = res.data.data.info.site_title;
          uni.setStorageSync("title", res.data.data.info.site_title);
          uni.setStorageSync("logo", this.logoUrl);
          uni.setStorageSync("loginVolid", this.loginVolid);
          uni.setStorageSync("filing_wartermark", res.data.data.filing_wartermark);
          if(res.data.data.partner_popup) this.changehomeModel(res.data.data.partner_popup);
        },
        true
      );
    },
     // 判断是否在展示时间范围内
    isInTimeRange(data) {
      const now = new Date();
      const startTime = new Date(data.start_time);
      const endTime = new Date(data.end_time);
      return now >= startTime && now <= endTime;
    },
    // 修改首页弹框状态
    changehomeModel(data) {
      // 如果没有启用弹框或不在有效时间范围内，则不显示
      if(data.is_enabled !== 1 || !this.isInTimeRange(data)) return;
      this.homeModelPath = data.image_path;
      this.homeredirectContent = data.redirect_content;
      if(data.type === 1) {
        // 每日首次展示
        const today = this.parseTime(new Date() / 1000); // 获取今天的日期
        const lastShownDate = uni.getStorageSync("lastDialogShownDate");
        // 如果今天没展示过，则展示弹框
        if (lastShownDate !== today) {
          this.homeModelShow = true;
          uni.setStorageSync("lastDialogShownDate", today); // 记录展示的日期
        }
      }else {
        // 每次进入展示
        this.homeModelShow = true;
      }
    },
    // 关闭首页弹框
    homeModelClose() {
      this.homeModelShow = false;
    },
    // 首页图片弹框点击
    homeModelImgClick() {
      let jumpOptions = ["","../../subpack/user/coupon/coupon_center","/subpack/user/integral/integral_shop",""];
      if(jumpOptions[this.homeredirectContent - 1]) {
        uni.navigateTo({
          url: jumpOptions[this.homeredirectContent - 1],
        });
        this.homeModelShow = false;
      }
    },
    // 获取商品
    getCommodity() {
      let params = {
        page: this.page,
        size: this.num,
        id: this.subjectIndex
      }
      this.goodsLoading = true;
      $https("GETN", "getRecommendCommodity", params, (res)=> {
        this.goodsLoading = false;
        if(res.data.errcode == 0) {
          // 如果是第一页，重置商品列表
          if(this.page == 1) {
            this.goodsList = [];
          }
          const data = res.data.data;
          this.display_row = data.list.style || 2;
          this.subjectList = data.list.subject_list;
          // 如果没有商品列表，直接返回
          if(!this.subjectList.length) return;
          // 获取当前专题的商品数据并处理价格
          const subject = this.subjectList[this.subjectIndex];
          let commodityList = subject.commodity_list || [];
          // 总商品数
          this.alltotal = subject.count;
          // 更新商品列表
          this.goodsList = [...this.goodsList, ...this.changePrice(commodityList)];
        } else {
          uni.showToast({
            icon: "none",
            title: res.data.errmsg,
          });
        }
      },this.loginVolid);
    },
    handMore() {
      if (this.goodsList.length < this.alltotal && !this.goodsLoading) {
        this.page++;
        this.getCommodity();
      }
    },
    // 修改分类
    changeSubject(item,index) {
      if(this.subjectIndex == index) return;
      this.page = 1;
      this.goodsList = [];
      this.subjectIndex = index;
      this.getCommodity();
    },
    //处理价格规格sku
    changePrice(data) {
      var array = JSON.parse(JSON.stringify(data));
      for (let i in array) {
        //算出价格范围
        if (array[i].spu.length > 1) {
          // var min, max;
          // min = array[i].spu[0].market_price;
          // if (array[i].spu[1].market_price < min) {
          // 	max = Number(array[i].spu[0].market_price);
          // 	min = Number(array[i].spu[1].market_price);
          // } else {
          // 	max = Number(array[i].spu[1].market_price);
          // 	min = Number(array[i].spu[0].market_price);
          // }
          // for (let y in array[i].spu) {
          // 	if (Number(array[i].spu[y].market_price) < min) {
          // 		min = Number(array[i].spu[y].market_price)
          // 	} else if (Number(array[i].spu[y].market_price) > max) {
          // 		max = Number(array[i].spu[y].market_price);
          // 	}
          // }
          let bol1 = array[i].spu.some((e) => {
            return e.current_price == 1;
          });
          let bol2 = array[i].spu.every((e) => {
            return e.current_price == 1;
          });
          let arr = [];
          array[i].spu.forEach((e) => {
            if (e.current_price != 1) {
              arr.push(e.market_price);
            }
          });
          let max = Math.max(...arr);
          let min = Math.min(...arr);
          // console.log(max,min);
          if (bol2) {
            array[i].showPrice = "时价";
          } else if (bol1) {
            array[i].showPrice = `时价~${max.toFixed(2)}`;
          } else {
            array[i].showPrice = `￥${min.toFixed(2)}~${max.toFixed(2)}`;
          }
        } else if (array[i].spu.length == 1) {
          //是时价
          if (array[i].spu[0].current_price == 1) {
            array[i].showPrice = "时价";
          } else {
            array[i].showPrice = "¥" + array[i].spu[0].market_price;
          }
          //只有一个规格时显示起订量、库存
          array[i].minimum = array[i].spu[0].minimum;
          array[i].designated_inventory = array[i].spu[0].designated_inventory;
          array[i].inventory_left = array[i].spu[0].inventory_left;
        }
        array[i].willBuyNum = array[i].num_cart_count;
      }
      return array;
    },

    detailPage(id) {
      //没有配置跳转的商品，id为0
      if (id) {
        uni.navigateTo({
          url: `../../subindex/index/shopdetail?id=${id}`,
        });
      }
    },

    addToCart(goodsId, spuId, num, index) {
      var options = {
        goods_id: goodsId,
        spu_id: spuId,
        num,
      };
      $https("POSTN", "changeCart", options, (res) => {
        if (res.data.errcode == 0) {
          this.goodsList[index].willBuyNum = Number(num);
          this.$refs.tabar.changetag(res.data.data.all_cart_num);
        } else {
          uni.showToast({
            title: res.data.errmsg,
            icon: "none",
          });
        }
      });
    },
    //显示小购物车
    showCart(index) {
      var data = this.goodsList[index];
      this.$refs.minicart.open(data);
    },
    //改变底部导航栏购物车tag
    changeTabBarTag(num) {
      this.$refs.tabar.changetag(num);
    },
    toPartDetail(name, id) {
      uni.navigateTo({
        url: `/subindex/index/subject?id=${id}&name=${name}`,
      });
    },
    toCheapSale() {
      uni.navigateTo({
        url: "/subindex/index/cheap_sale",
      });
    },
    parseTime(time) {
      time = time * 1000;
      var date = new Date(time);
      var year = date.getFullYear(),
        month =
          date.getMonth() + 1 < 9
            ? "0" + (date.getMonth() + 1)
            : date.getMonth() + 1,
        day = date.getDate() < 9 ? "0" + date.getDate() : date.getDate();
      return `${year}-${month}-${day}`;
    },
    //跳转
    navigate(item) {
      if (item.name == "联系客服") {
        this.showtel = true;
        this.telphone = item.route;
        this.corpId = item.corpId;
      }
      if (item.wx_url != null) {
        this.showline = true;
        this.wx_url = item.wx_url;
      }
      if (item.name == "意见反馈" && !uni.getStorageSync("copartner_token")) {
        uni.redirectTo({
          url: "/subpack/account/login",
        });
      } else if (item.type == 2) {
        //跳到分类
        uni.reLaunch({
          url: `/pages/tabar/classify?navid=${item.nav_id}`,
        });
      } else {
        uni.navigateTo({
          url: `/subpack/${item.route}`,
        });
      }
    },
    // 跳转
    jump(item) {
      if (item.jump_type == 1 && item.goods_id) {
        uni.navigateTo({
          url: `../../subindex/index/shopdetail?id=${item.goods_id}`,
        });
      } else if (item.jump_type == 2) {
        uni.navigateTo({
          url: `../../subpack/user/integral/integral_shop`,
        });
      } else if (item.jump_type == 3) {
        uni.reLaunch({
          url: `/pages/tabar/classify?navid=${item.category_id}`,
        });
      } else if (item.jump_type == 4) {
        uni.reLaunch({
          url: `/pages/tabar/classify?navid=${item.category_p_id}&category_id=${item.category_id}`,
        });
      }
    },
    //选择是客服电话还是在线客服
    onselect(type) {
      if (type == 1) {
        uni.makePhoneCall({
          phoneNumber: this.telphone,
          success: (res) => {},
          fail: (res) => {
            this.showtel = false;
          },
        });
      } else {
        if (this.wx_url != "") {
          let url = this.wx_url; //获取地址栏路径
          let temp1 = url.split("//"); //对url地址进行分割

          // #ifdef H5
          window.open(`https://${temp1[1]}`);
          this.showtel = false;
          // #endif

          // #ifdef MP-WEIXIN
          wx.openCustomerServiceChat({
            extInfo: {
              url: url,
            },
            corpId: this.corpId,
            success(res) {},
          });
          this.showtel = false;
          // #endif

          // #ifdef APP-PLUS
          plus.runtime.openURL(`https://${temp1[1]}`);
          this.showtel = false;
          // #endif
        }
      }
    },

    toCouponMy() {
      uni.navigateTo({
        url: "/subpack/user/coupon/coupon_my",
      });
    },

    alertInfo(info) {
      this.info.value = info;
      this.info.show = true;
    },
    // 去门店地图
    toGiude() {
      uni.navigateTo({
        url: "/pages/tabar/guide",
      });
    },
    hexToRgba(hex,opacity) {
      // 移除前缀 '#'，然后转换为 RGB 格式
      let r = parseInt(hex.slice(1, 3), 16);
      let g = parseInt(hex.slice(3, 5), 16);
      let b = parseInt(hex.slice(5, 7), 16);
      return `rgba(${r}, ${g}, ${b}, ${opacity})`;
    }
  },
  onReachBottom() {
  },
  onShareAppMessage(res) {
    return {
      title: this.wxshare.title,
      path: "pages/tabar/index",
      imageUrl: "",
      desc: "",
      content: "",
    };
  },
  onPageScroll(e) {
    if(!this.$refs.mySearch) return;
    let mySearch = this.$refs.mySearch;
    mySearch.background = this.hexToRgba(app.themeConfig.text_color2,e.scrollTop / 200);
  },
};
</script>

<style lang="scss" scoped>
$bgImage: var(--theme-bg);
$saleBgImage: var(--theme-sale-bg);
$fontColor: var(--theme-text-color);
$buttonColor: var(--theme-time-color);
$bgColor: var(--theme-bg-color);
$length: var(--length) / 5;
/deep/.u-drawer {
  overflow: unset !important;
}
/deep/.search_style {
  background: transparent;
  border-bottom: 0;
}
.page {
  position: relative;
  font-size: 24rpx;
  box-sizing: border-box;
  min-height: 100vh;
  background: $bgColor;
  background-image: $bgImage;
  background-repeat: no-repeat;
  background-position: 0 0;
  background-size: 100% 700rpx;

  .content {
    //#ifndef MP-WEIXIN
    margin-top: var(--status-bar-height);
    //#endif
  }

  .banner {
    @include container(100%, 258rpx);
    margin-bottom: 20rpx;
    padding: 0 30rpx;
   
    .swiper {
      @include container(100%, 258rpx);
      border-radius: 10rpx;
      overflow: hidden;
    }
    .img {
      @include container(100%, 258rpx);
    }

    uni-swiper {
      height: 100%;
    }
  }
  .bannerTop {
    //#ifdef MP-WEIXIN
    margin-top: calc(700rpx - 120rpx - 258rpx - 20rpx - var(--menusystemheight));
    //#endif
    //#ifndef MP-WEIXIN
    margin-top: calc(700rpx - 100rpx - 120rpx - 258rpx - 20rpx);
    //#endif
  }

  .info {
    @include container(100%);
    padding: 0 30rpx;
    .info-content {
      @include container(100%, auto, transparent);
      padding: 20rpx 12rpx;
      border-radius: 10rpx;
      .info-icon {
        @include container(48rpx, 48rpx, $buttonColor);
        @include flex-layout(center, center);
        border-radius: 24rpx;
        .icon {
          @include container(75%, 75%);
        }
      }
      .text {
        flex: 1;
        margin: 0;
        padding: 0;
      }
    }
  }

  .part {
    @include container(100%, auto, transparent);
    padding: 0 30rpx;
    .part-swiper {
      margin-top: 20rpx;
      min-height: 130rpx;
      &.line-1 {
        height: 190rpx;
      }
      &.line-2 {
        height: 360rpx;
      }
      &.line-3 {
        height: 230rpx;
      }
      &.line-4 {
        height: 410rpx;
      }
    }
  }

  .part_box {
    overflow: hidden;
    margin: 20rpx 0;
    display: grid;
    grid-template-rows: repeat($length, 152rpx);
    grid-template-columns: repeat(5, 1fr);
    justify-items: center;
    border-radius: 10rpx;

    .part {
      @include flex-layout(center, center);
      float: left;
      flex-direction: column;
      font-size: 24rpx;
      width: 110rpx;
      margin: 20rpx 0;
      // margin-bottom: 36rpx;
      .part_img {
        @include container(94rpx, 94rpx);
        border-radius: 94rpx;
        margin-bottom: 10rpx;
      }
      .part_text {
        @include container(140rpx);
        @include text-ellipsis;
        @include font-style(30rpx, $fontColor);
        text-align: center;
      }
    }
  }

  .activity {
    @include container(100%);
    padding: 0 30rpx;
    .activity_box {
      @include container(100%, auto, #ffffff);
      border-radius: 10rpx;
      padding: 18rpx;
      margin-top: 20rpx;
      .title {
        @include font-style(36rpx, #191919);
        margin-bottom: 20rpx;
      }
      image {
        border-radius: 10rpx;
      }
      .style1 {
        image {
          @include container(100%, 348rpx);
        }
      }
      .style2 {
        image {
          @include container(320rpx, 400rpx);
        }
      }
      .style3 {
        height: 316rpx;
        .left {
          @include container(40%, 316rpx);
          image {
            @include container(100%, 316rpx);
          }
        }
  
        .right {
          @include container(58%, 100%);
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          image {
            @include container(100%, 153rpx);
          }
        }
      }
    }
  }

  .homeCategory {
    @include container(100%, 88rpx, $bgColor);
    padding: 20rpx 30rpx;
    position: sticky;
    left: 0;
    top: calc(120rpx + 100rpx);
    z-index: 998;
    // #ifdef MP-WEIXIN
    top: calc(120rpx + var(--menusystemheight));
    // #endif
    .category {
      display: flex;
      .category-name {
        @include container(auto, 48rpx);
        @include font-style(26rpx, $fontColor);
        line-height: 48rpx;
        flex-shrink: 0;
        border-radius: 24rpx;
        padding: 8rpx 18rpx;
        margin-right: 20rpx;
        &.active {
          background-color: $buttonColor;
          color: #ffffff;
        }
        &:last-child {
          margin-right: 0;
        }
      }
    }
  }

  .goodsScroll {
    height: calc(100vh - 120rpx - 100rpx - 120rpx - 88rpx - env(safe-area-inset-bottom));
    // #ifdef MP-WEIXIN
    height: calc(100vh - 120rpx - var(--menusystemheight) - 120rpx - 88rpx - env(safe-area-inset-bottom));
    // #endif
  }
  .recommend_box {
    width: 100%;
    padding: 0 30rpx;
    position: relative;
    overflow: hidden;
    display: grid;
    justify-content: space-between;
    grid-row-gap: 20rpx;
    .goods {
      float: left;
      position: relative;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      background: #fff;
      border-radius: 10rpx;
      box-sizing: border-box;
      overflow: hidden;
      position: relative;
      .img {
        display: flex;
        justify-content: center;
        image {
          width: 100%;
          height: 100%;
        }
      }
      .tags {
          position: absolute;
          top: 20rpx;
          right: 20rpx;
          z-index: 10;
          display: inline-flex;
          align-items: center;
          .tag {
            @include container(auto, 35rpx, #FF0000);
            @include font-style(20rpx, #ffffff);
            @include flex-layout(center, center);
            line-height: 35rpx;
            padding: 0 6rpx;
            border-radius: 6rpx;
            margin-right: 8rpx;
            &:last-child {
              margin-right: 0;
            }
          }
        }
      .goods-content {
        padding: 10rpx 20rpx;
        box-sizing: border-box;
        .name {
          @include font-style(32rpx, #333333, bold);
          @include ellipsis-mult(2);
          width: 90%;
          margin-bottom: 8rpx;
        }
        .detail {
          @include font-style(24rpx, #666666);
          margin-bottom: 8rpx;
        }

        .price {
          @include flex-layout(space-between,center);
          height: 38rpx;

          .unit {
            @include font-style(24rpx, red);
            line-height: 38rpx;
          }

          .icon {
            position: absolute;
            z-index: 1;
            bottom: 12rpx;

            &.logo {
              width: 80rpx;
              left: 14rpx;
            }

            &.shop {
              @include container(55rpx, 55rpx);
              right: 14rpx;
            }
          }
        }
      }
    }
    .noGoods {
      @include container(320rpx, auto);
      display: flex;
      flex-direction: column;
      align-items: center;
      margin: 0 auto;
      color: #cccccc;
      image {
        @include container(100%, 240rpx);
      }
    }
  }

  .moreText {
    margin-top: 20rpx;
    @include container(100%, 40rpx);
    @include flex-layout(center, center);  
    @include font-style(28rpx, #cccccc);
    .goodsLoading {
      margin-right: 10rpx;
    }
  }
  
  .sale {
    width: 100%;
    padding: 0 30rpx;
    .sale_box {
      @include container(100%, 575rpx);
      @include flex-layout(flex-end, flex-end);
      flex-direction: column;
      background-image: $saleBgImage;
      background-size: 100% 100%;
      background-repeat: no-repeat;
      border-radius: 10rpx;
      padding: 12rpx 22rpx;
      margin-top: 20rpx;
      .time {
        @include container(auto, 46rpx, $bgColor);
        @include font-style(24rpx, $fontColor);
        padding: 8rpx 16rpx;
        border-radius: 23rpx;
        display: inline-flex;
        align-items: center;
        /deep/.u-countdown-colon, /deep/.u-countdown-time {
          font-size: 24rpx !important;
          color: $fontColor !important;
          padding: 2rpx;
        }
        .text {
          margin-right: 8rpx;
        }
      }
      .sale_content {
        width: 100%;
        display: grid;
        grid-template-columns: repeat(3,200rpx);
        justify-content: space-between;
        margin-top: 10rpx;
        .goods {
          @include container(200rpx, 300rpx, #ffffff);
          @include flex-layout(center, center);
          flex-direction: column;
          padding: 20rpx 0;
          line-height: 40rpx;
          box-shadow: 0px 4px 16px 2px rgba(216, 216, 216, 0.38);
          border-radius: 10rpx;
          .img {
            @include container(140rpx, 140rpx);
          }
  
          .name {
            @include font-style(26rpx, #191919, bold);
            @include text-ellipsis;
            width: 90%;
            text-align: center;
            margin: 10rpx 0;
          }
  
          .unit {
            @include font-style(20rpx, #e84b4b);
            .price {
              font-size: 22rpx;
            }
            &.old {
              color: #cccccc;
              transform: sacle(0.9);
              text-decoration: line-through;
            }
          }
        }
      }
    }
  }
}

/deep/.u-mask-show {
  opacity: 1 !important;
}

.warp {
  @include flex-layout(center, center);
  flex-direction: column;
}

.rect {
  position: relative;
  height: auto;
}

.pics {
  position: relative;
  height: auto;
}

.pics image {
  width: 500rpx;
  height: 750rpx;
  display: block;
  margin: 0 auto;
  margin-top: 150rpx;
}

.abos {
  position: absolute;
  left: -36rpx;
  top: 290rpx;
  height: auto;
}

.copon_box {
  width: 570rpx;
  height: 164rpx;
  background-image: url(../../static/image/coupon.png);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  padding: 0 30rpx;
  margin-bottom: -30rpx;
  transform: scale(0.7);

  .left {
    min-height: 150rpx;
    width: 40rpx;
    word-wrap: break-word;
    font-size: 28rpx;
    line-height: 40rpx;
    border-radius: 4rpx;
    text-align: center;
    padding: 10rpx 0;
    transform: scale(0.8);
  }

  .right {
    width: 40rpx;
    word-wrap: break-word;
    font-size: 22rpx;
    height: auto;
    border: 1px solid #fff;
    border-radius: 6rpx;
    text-align: center;
    padding: 10rpx 0;
    margin-left: 40rpx;
  }

  .center {
    flex: 1;

    .center_left {
      text-align: center;
      width: 50%;

      .price {
        font-size: 40rpx;
        font-weight: bold;
      }

      .info {
        text-align: center;
        color: #a4a4a4;
        font-size: 24rpx;

        .info_text {
          text-decoration: underline;
          margin-left: 4rpx;
        }
      }
    }

    .center_right {
      text-align: center;
      width: 50%;

      .rule {
        font-size: 24rpx;
      }

      .limit {
        font-size: 30rpx;
        transform: scale(0.8);
      }

      .time {
        font-size: 28rpx;
        border-radius: 16rpx;
        padding: 7rpx 12rpx;
        transform: scale(0.7);
      }
    }
  }

  &.copon {
    .left {
      background: #f6d32d;
      color: #c6272a;
    }

    .right {
      color: #f6d32d;
      border-color: #f6d32d;
    }

    .center_left {
      .price {
        color: #c6272a;
      }
    }

    .center_right {
      color: #757575;

      .rule {
        color: #191919;
      }

      .time {
        background: #e9adae;
      }
    }
  }
}

.tel-flex {
  height: auto;
}

.flex-box {
  @include flex-layout(center, center);
  padding: 24rpx 0rpx;
}

.tel-pic {
  @include container(40rpx, 40rpx);
  margin-right: 30rpx;
}

.lf-border {
  border-top: 1px solid #cccccc;
}

.txt-size {
  font-size: 28rpx;
}

/deep/.u-notice-text {
  font-size: 26rpx !important;
}
</style>